<?php

namespace ORM;

use Database\Connection;

class SchemaAnalyzer {
    protected $connection;
    protected $schemaCache = [];
    
    /**
     * 构造函数
     */
    public function __construct(Connection $connection) {
        $this->connection = $connection;
    }
    
    /**
     * 获取表的列信息
     */
    public function getColumns($table) {
        // 如果已缓存，直接返回
        if (isset($this->schemaCache[$table])) {
            return $this->schemaCache[$table];
        }
        
        $pdo = $this->connection->getPdo();
        $driver = $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
        
        // 根据不同的数据库驱动获取表结构
        switch ($driver) {
            case 'mysql':
                return $this->getMySqlColumns($table);
            case 'sqlite':
                return $this->getSqliteColumns($table);
            default:
                throw new \Exception("不支持的数据库驱动: {$driver}");
        }
    }
    
    /**
     * 获取MySQL表的列信息
     */
    protected function getMySqlColumns($table) {
        $sql = "SHOW COLUMNS FROM {$table}";
        $statement = $this->connection->query($sql);
        $columns = $statement->fetchAll();
        
        $result = [];
        foreach ($columns as $column) {
            $type = $this->parseColumnType($column['Type']);
            
            $result[$column['Field']] = [
                'name' => $column['Field'],
                'type' => $type['type'],
                'length' => $type['length'],
                'nullable' => $column['Null'] === 'YES',
                'default' => $column['Default'],
                'primary' => $column['Key'] === 'PRI',
                'auto_increment' => strpos($column['Extra'], 'auto_increment') !== false
            ];
        }
        
        // 缓存结果
        $this->schemaCache[$table] = $result;
        
        return $result;
    }
    
    /**
     * 获取SQLite表的列信息
     */
    protected function getSqliteColumns($table) {
        $sql = "PRAGMA table_info({$table})";
        $statement = $this->connection->query($sql);
        $columns = $statement->fetchAll();
        
        $result = [];
        foreach ($columns as $column) {
            $type = $this->parseColumnType($column['type']);
            
            $result[$column['name']] = [
                'name' => $column['name'],
                'type' => $type['type'],
                'length' => $type['length'],
                'nullable' => $column['notnull'] == 0,
                'default' => $column['dflt_value'],
                'primary' => $column['pk'] == 1,
                'auto_increment' => $column['pk'] == 1 // SQLite主键通常是自增的
            ];
        }
        
        // 缓存结果
        $this->schemaCache[$table] = $result;
        
        return $result;
    }
    
    /**
     * 解析列类型
     */
    protected function parseColumnType($typeString) {
        $type = strtolower($typeString);
        $length = null;
        
        // 提取类型和长度，如varchar(255)
        if (preg_match('/^([a-z]+)(\(([0-9]+)(,[0-9]+)*\))?/', $type, $matches)) {
            $type = $matches[1];
            if (isset($matches[3])) {
                $length = (int) $matches[3];
            }
        }
        
        // 映射数据库类型到PHP类型
        $phpType = $this->mapToPhpType($type);
        
        return [
            'type' => $phpType,
            'length' => $length
        ];
    }
    
    /**
     * 将数据库类型映射到PHP类型
     */
    protected function mapToPhpType($dbType) {
        $typeMap = [
            // 整数类型
            'tinyint' => 'integer',
            'smallint' => 'integer',
            'mediumint' => 'integer',
            'int' => 'integer',
            'integer' => 'integer',
            'bigint' => 'integer',
            
            // 浮点类型
            'float' => 'float',
            'double' => 'float',
            'decimal' => 'float',
            'numeric' => 'float',
            
            // 字符串类型
            'char' => 'string',
            'varchar' => 'string',
            'tinytext' => 'string',
            'text' => 'string',
            'mediumtext' => 'string',
            'longtext' => 'string',
            
            // 日期时间类型
            'date' => 'date',
            'datetime' => 'datetime',
            'timestamp' => 'timestamp',
            'time' => 'time',
            'year' => 'integer',
            
            // 布尔类型
            'boolean' => 'boolean',
            'bool' => 'boolean',
            
            // 二进制类型
            'blob' => 'binary',
            'tinyblob' => 'binary',
            'mediumblob' => 'binary',
            'longblob' => 'binary',
            
            // JSON类型
            'json' => 'array'
        ];
        
        return isset($typeMap[$dbType]) ? $typeMap[$dbType] : 'string';
    }
    
    /**
     * 获取表的主键
     */
    public function getPrimaryKey($table) {
        $columns = $this->getColumns($table);
        
        foreach ($columns as $name => $column) {
            if ($column['primary']) {
                return $name;
            }
        }
        
        return null; // 没有主键
    }
    
    /**
     * 检查表是否存在
     */
    public function tableExists($table) {
        $pdo = $this->connection->getPdo();
        $driver = $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
        
        try {
            switch ($driver) {
                case 'mysql':
                    $sql = "SHOW TABLES LIKE '{$table}'";
                    break;
                case 'sqlite':
                    $sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='{$table}'";
                    break;
                default:
                    throw new \Exception("不支持的数据库驱动: {$driver}");
            }
            
            $statement = $this->connection->query($sql);
            return $statement->rowCount() > 0;
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * 清除表结构缓存
     */
    public function clearCache($table = null) {
        if ($table === null) {
            $this->schemaCache = [];
        } else {
            unset($this->schemaCache[$table]);
        }
    }
}